import axios, { AxiosInstance, AxiosError, AxiosResponse, AxiosRequestConfig } from "axios";
// import { ElMessage } from "element-plus";
import { SCMessage } from "@sribd/sc-ui";
import { useRoute, useRouter } from "vue-router";
import { getToken } from "./auth";

const instance: AxiosInstance = axios.create({
    timeout: 6000, // 设置超时
    headers: {
        "Content-Type": "application/json;charset=UTF-8;",
    },
});

instance.interceptors.request.use((config: AxiosRequestConfig<any>) => {
    if (getToken()) {
        config.headers!["Authorization"] = getToken();
    }
    return config;
});

instance.interceptors.response.use(
    async (res: AxiosResponse) => {
        const headers = res.headers;
        if (headers["content-type"] === "application/octet-stream;charset=utf-8") {
            // 二进制文件下载处理
            return {
                fileName: headers["content-disposition"]?.split("filename=")?.[1] || "",
                data: res.data,
            };
        }

        // 请求状态码为200
        if (res.status === 200) {
            // 判断响应状态码
            const { code } = res.data;
            switch (+code) {
                case 0:
                    return Promise.resolve(res.data);
                default:
                    return Promise.reject(res.data);
            }
        }
        return Promise.reject(res);
    },
    async (error: AxiosError) => {
        const router = useRouter();
        const route = useRoute();
        // 登录超时
        if (error.response?.status === 401) {
            router.push(`/login?redirect=${route.fullPath}`);
        }
        // 响应错误
        if (error.code === "ERR_NETWORK") {
            SCMessage({
                type: "error",
                message: "请检查网络连接",
                background: true,
            });
        }
        const data = error.response?.data || {};
        const errorData = {
            ...error.response,
            ...data,
        };
        return Promise.reject(errorData);
    },
);

export default instance;
